from pyalgotrade.feed import csvfeed
from pyalgotrade import strategy
from pyalgotrade.stratanalyzer import returns
from pyalgotrade.stratanalyzer import sharpe
from pyalgotrade.stratanalyzer import drawdown
from pyalgotrade.stratanalyzer import trades
from pyalgotrade import broker

from pyalgotrade.barfeed.csvfeed import GenericBarFeed
from pyalgotrade.bar import Frequency

from pyalgotrade.technical import ma
from pyalgotrade.technical import cross

'''
feed=csvfeed.Feed("Date","%Y-%M-%d")
feed.addValuesFromCSV('600546_rename.csv')
'''
feed=GenericBarFeed(Frequency.DAY)
feed.addBarsFromCSV('600546','600546_rename.csv')


class SMACrossOver(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, smaPeriod):
        super(SMACrossOver, self).__init__(feed)
        self.__instrument = instrument
        self.__position = None
        # We'll use adjusted close values instead of regular close values.
        self.setUseAdjustedValues(True)
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__sma = ma.SMA(self.__prices, smaPeriod)

    def getSMA(self):
        return self.__sma

    def onEnterCanceled(self, position):
        self.__position = None

    def onExitOk(self, position):
        self.__position = None

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position.exitMarket()

    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if cross.cross_above(self.__prices, self.__sma) > 0:
                shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
                # Enter a buy market order. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, shares, True)
        # Check if we have to exit the position.
        elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
            self.__position.exitMarket()

# 手续费
'''
broker_commision = broker.backtesting.TradePercentage(0.0003)
brk = broker.backtesting.Broker(1000000, feed, broker_commision)
'''

myStrategy = SMACrossOver(feed, '600546', 60)

retAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(retAnalyzer)
sharpeAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeAnalyzer)
drawDownAnalyzer = drawdown.DrawDown()
myStrategy.attachAnalyzer(drawDownAnalyzer) 
tradesAnalyzer = trades.Trades()
myStrategy.attachAnalyzer(tradesAnalyzer)

'''
from pyalgotrade import plotter
plter = plotter.StrategyPlotter(myStrategy)
plter.getOrCreateSubplot("return").addDataSeries("retuens", retAnalyzer.getReturns())
plter.getOrCreateSubplot("CumReturn").addDataSeries("CumReturn",retAnalyzer.getCumulativeReturns)
'''

myStrategy.run()